#include "client.h"
/************************客服端登录，以及服务端验证****************/
// 功能：获取用户输入的username和passwd，发送给服务端，接收鉴权结果
// 传入传出参数：is_User: 0-失败 1-成功
//返回值：0-登录成功 -1-登录失败

int login(userinfo_t* userinfo, int sockfd)
{
    int is_User = 0;
    
    int wrongCount = 0; // 登录出错次数
    while (is_User == 0) { 
        memset(userinfo->username, 0, sizeof(userinfo->username));
        memset(userinfo->password, 0, sizeof(userinfo->password));

        // 用户登录
        printf("输入用户名:");
        fflush(stdout);//清缓存
        read(STDIN_FILENO, userinfo->username, sizeof(userinfo->username));
        userinfo->username[strlen(userinfo->username)-1] = '\0';
        printf("输入密码:");
        fflush(stdout);
        read(STDIN_FILENO, userinfo->password, sizeof(userinfo->password));
        userinfo->password[strlen(userinfo->password)-1] = '\0';

        // 发送登录信息
        train_t train;
        train.length = strlen(userinfo->username);
        memcpy(train.buf, userinfo->username, train.length);
        send(sockfd, &train, sizeof(train_t), MSG_NOSIGNAL);
        
        train.length = strlen(userinfo->password);
        memcpy(train.buf, userinfo->password, train.length);
        send(sockfd, &train, sizeof(train_t), MSG_NOSIGNAL); // 目前明文传输，后续待扩展

        // 等待接收鉴权结果
        printf("正在登录...\n");
        recv(sockfd, &is_User, sizeof(int), 0);
        if (is_User != 0) { // 鉴权成功
            printf("登录成功!\n");
            return 0;
        }
        
        wrongCount++;
        if (wrongCount == 5) { // 5次失败
            printf("错误5次,已关闭客户端！\n");
            return -1;
        }
    }
    
    return 0;
  
}

